import 'package:flutter/material.dart';

//数据共享!定义
class MyData extends InheritedWidget {
  MyData({this.data, Widget child}) : super(child: child);
  final int data; //需要在子Widget中共享的数据!

  //提供一个方法让子Widget访问的共享数据!
  static MyData of(BuildContext context) {
    print('定义');
    return context.dependOnInheritedWidgetOfExactType<MyData>();
  }

  @override
  bool updateShouldNotify(MyData oldWidget) {
    return oldWidget.data != data;
  }
}

class InheritedDemo extends StatefulWidget {
  @override
  _InheritedDemoState createState() => _InheritedDemoState();
}

class _InheritedDemoState extends State<InheritedDemo> {
  int count = 1;

  @override
  Widget build(BuildContext context) {
    print('给 子widget 共享');
    return MyData(//共享数据初始化
      data: count,
      child: Column(
        children: <Widget>[
          Test1(),
          RaisedButton(
            child: Text('我是按钮'),
            //setState!

            onPressed: () => setState(() {
              count++;
            }),
          )
        ],
      ),
    );
  }
}

class Test1 extends StatelessWidget {
//  final count;
//  Test1(this.count);
  @override
  Widget build(BuildContext context) {
    return Test2();
  }
}

class Test2 extends StatelessWidget {
//  final count;
//  Test2(this.count);
  @override
  Widget build(BuildContext context) {
    return Test3();
  }
}

class Test3 extends StatefulWidget {
//  final count;
//  Test3(this.count);
  @override
  _Test3State createState() => _Test3State();
}

class _Test3State extends State<Test3> {
  @override
  Widget build(BuildContext context) {
    print('掉用');
    return Text(MyData.of(context).data.toString());//共享数据掉用
  }

  @override
  void didChangeDependencies() {
    print('didChangeDependencies');
    super.didChangeDependencies();
  }
}
